(ns cljstalk2011.memshow
  (:require
   [twitterbuzz.dom_helpers :as dh]
   [goog.net.XhrIo :as xhr]
   [goog.dom :as dom]
   [goog.Uri :as uri]
   [goog.Timer :as timer]
   [goog.events :as events]
   [cljs.reader :as reader]))

(defn log [s]
 (let [t (dom/getElement "log")]
  (dom/append t (str s "\n"))))

(defn add-row [row]
 (dom/append
  (dom/getElement "tbl")
  (dh/build [:tr [:td (:MemTotal row)]
   [:td (:MemFree row)]
   [:td (:Buffers row)]
   [:td (:Cached row)]])))

(defn on-data-receive [message]
  (log "on-data-receive")
  (add-row (reader/read-string
  	   (. message/target (getResponseText)))))

(defn fetch-data []
  (let [uri (goog.Uri. "http://localhost:8080/")]
    (log "sending request")
    (xhr/send uri on-data-receive)))

(defn  ^{:export run_demo} run-demo []
  (log "run-demo")
  (let [timer (goog.Timer. 5000)]
     (do (fetch-data)
     (. timer (start))
     (events/listen timer goog.Timer/TICK fetch-data))))
